package com.ftd.daoImp;

import com.ftd.dao.BookDao;
import com.ftd.dao.BorrowDao;
import com.ftd.config.RorrowConfig;
import com.ftd.model.Borrow;
import com.ftd.model.BorrowPK;
import com.ftd.utils.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by apple on 2016/12/8.
 */
@Repository("BorrowDaoImp")
public class BorrowDaoImp extends BaseHibernateDaoImp  implements BorrowDao{

    private Session session;
    @Autowired
    private Borrow borrow;
    @Autowired
    private BorrowPK borrowPK;
    @Autowired
    private BookDao bookDao;

    @Override
    public void borrow(int userId, int bookId) {
        try{

            session = getSession();
            /**
             * borrow表修改,先判断是否已存在
             */
            borrowPK.setUserId(userId);
            borrowPK.setBookId(bookId);
            if (session.get(Borrow.class,borrowPK) != null){
                borrow = session.get(Borrow.class,borrowPK);
                borrow.setBorrowCount(borrow.getBorrowCount()+1);
            } else {
                borrow.setUserId(userId);
                borrow.setBookId(bookId);
                borrow.setLeftDay(RorrowConfig.HOLD_DAY);
                borrow.setBorrowCount(borrow.getBorrowCount()+1);
            }
            session.persist(borrow);
//            session.getTransaction().commit();

//            book表Count更改;这么写有重大错误,应该用注入的方式获取bookdao;使用spring,就不应该出现new
//            new BookDaoImp().updateBookByIdAndCount(bookId,-1);
            bookDao.updateBookByIdAndCount(bookId,-1);

        }catch (Exception e){
            e.printStackTrace();
        } finally {
            borrow = null;
        }

    }

    @Override
    public void back(int userId, int bookId) {

    }

    @Override
    public void autoUpdate() {
        session = getSession();
        String hql = "from Borrow";
        Query query = session.createQuery(hql);
        List<Borrow> borrowList = query.list();
        for (Borrow borrow:
             borrowList) {
            int leftDay = borrow.getDelayDay()-1;
            //如果剩余天数已经小于0了,那就不继续减少leftDay,而去增加delayDay
            if (leftDay <0){
                borrow.setDelayDay(leftDay);
            } else {
                borrow.setLeftDay(leftDay);
            }
        }

    }

    @Override
    public void closeSession(){
        HibernateUtil.closeSession();
    }


}
